package com.salmon.study.multithread;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.JdkFutureAdapters;
import com.google.common.util.concurrent.ListenableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.client.AsyncRestTemplate;

import java.util.concurrent.Executors;

public class AsyncHttpExample {

    private final static Logger LOGGER = LoggerFactory.getLogger(AsyncHttpExample.class);

    public static void main(String[] args) throws Exception {
        AsyncRestTemplate tp = new AsyncRestTemplate();
        org.springframework.util.concurrent.ListenableFuture<ResponseEntity<Object>> response = tp
                .getForEntity("http://www.baidu.com", Object.class);
        // 转换成Google的ListenableFuture
        ListenableFuture<ResponseEntity<Object>> listenInPoolThread = JdkFutureAdapters.listenInPoolThread(response);
        Futures.addCallback(listenInPoolThread, new FutureCallback<Object>() {
            @Override
            public void onSuccess(Object result) {
                System.err.println(result.getClass());
                System.err.printf("success", result);
            }

            @Override
            public void onFailure(Throwable t) {
                System.out.printf("failure");
            }
        }, Executors.newFixedThreadPool(10));
    }

    public String async() {
        AsyncRestTemplate template = new AsyncRestTemplate();
        String url = "http://localhost:8080/async/fivetime";//休眠5秒的服务
        //调用完后立即返回（没有阻塞）
        org.springframework.util.concurrent.ListenableFuture<ResponseEntity<String>> forEntity = template.getForEntity(url, String.class);
        //异步调用后的回调函数
        forEntity.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
            //调用失败
            @Override
            public void onFailure(Throwable ex) {
                LOGGER.error("=====rest response faliure======");
            }

            //调用成功
            @Override
            public void onSuccess(ResponseEntity<String> result) {
                LOGGER.info("--->async rest response success----, result = " + result.getBody());
            }
        });
        return "异步调用结束";
    }
}
